﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using AviagePortal.Entity;
// Call example   http://msstoresp12013/sites/ap/_layouts/15/AviagePortal/ApprovePage.aspx?recordId=1
namespace AviagePortal.Layouts.AviagePortal
{
    public partial class ApprovePage : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {          
            this.ErrorLabel.Visible = false;
            this.ApproveRecordPanel.Visible = false;
            this.ApproveButton.Visible = false;
            this.RejectButon.Visible = false;
            this.ApproveCommentsTextarea.Visible = false;
            this.ApproveByLabel.Visible = false;
            this.CommentsLabel.Visible = false;           
            string recordId = Request.QueryString["recordId"];
            SPGroup approveGroup = SPContext.Current.Web.SiteGroups["AviagePortalApprover"];
            if (!approveGroup.ContainsCurrentUser)
            {
                this.ErrorLabel.Visible = true;
            }
            else
            {
                int id = 0;
                if (!string.IsNullOrWhiteSpace(recordId) && int.TryParse(recordId, out id))
                {
                    SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
                    SPListItem item = approveRecords.GetItemById(id);
                    this.ApproveRecordPanel.Visible = true;

                    int length = "<div class=\"ExternalClass201E51BB23DD4D7D9CDCFE1379A784AA\">".Length;
                    ApproveRecordPanelChangeDiscriptionTextArea.InnerHtml = ("" + item["ChangeDescription"]).Substring(length).Replace("</div>", "");                    
                    ApproveRecordPanelCreateByLabel.Text = string.Format("Submitted by {0} at {1}", (new SPFieldUserValue(SPContext.Current.Web, "" + item["Created By"])).LookupValue, "" + item["Created"]);
                    if ("" + item["Status"] == ApproveStatus.Pending)
                    {
                        this.ApproveButton.Visible = true;
                        this.RejectButon.Visible = true;
                        this.CommentsLabel.Visible = true;
                        this.ApproveCommentsTextarea.Visible = true;
                    }
                    else if ("" + item["Status"] == ApproveStatus.Approved || "" + item["Status"] == ApproveStatus.Rejected)
                    {
                        this.CommentsLabel.Visible = true;
                        this.ApproveCommentsTextarea.Visible = true;
                        this.ApproveCommentsTextarea.Attributes.Add("readonly", "readonly");
                        this.ApproveCommentsTextarea.InnerHtml = ("" + item["ApproveComments"]).Substring(length).Replace("</div>", "");
                        this.ApproveByLabel.Visible = true;
                        if ("" + item["Status"] == ApproveStatus.Approved)
                        {
                            ApproveByLabel.Text = string.Format("Approved by {0} at {1}", (new SPFieldUserValue(SPContext.Current.Web, "" + item["ApprovedBy"])).LookupValue, "" + item["ApproveDate"]);
                        }
                        else
                        {
                            ApproveByLabel.Text = string.Format("Rejected by {0} at {1}", (new SPFieldUserValue(SPContext.Current.Web, "" + item["ApprovedBy"])).LookupValue, "" + item["ApproveDate"]);
                        }
                    }
                    else if ("" + item["Status"] == ApproveStatus.Canceled)
                    {
                        this.ApproveByLabel.Visible = true;
                        ApproveByLabel.Text = string.Format("Canceled by {0} at {1}", (new SPFieldUserValue(SPContext.Current.Web, "" + item["Modified By"])).LookupValue, "" + item["Modified"]);
                    }
                }
                else
                {
                    this.ErrorLabel.Visible = true;
                    this.ErrorLabel.Text = "Invalid parameter";
                }
            }
            
        }

        protected void ApproveButton_Click(object sender, EventArgs e)
        {
            SiteDataOperator.ApproveAll();
            string recordId = Request.QueryString["recordId"];
              SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
              SPListItem item = approveRecords.GetItemById(int.Parse(recordId));

              item["Status"] = ApproveStatus.Approved;
              item["ApproveDate"] = DateTime.Now;
              item["ApproveComments"] = this.ApproveCommentsTextarea.InnerText;
              item["ApprovedBy"] = new SPFieldUserValue(SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID,  SPContext.Current.Web.CurrentUser.Name);
              item.Update();
            // Send mail
              string mailBody = string.Format(@"<Div>Dear editors:</Div>
                                                  <Div>{0} have approved the request:</Div>
                                                  <Div>Change descriptin is:</Div>
                                                  <Div>{1}</Div>
                                                  <Div>Approve comment is: {2}</Div><br/><br/> 
                                                  <Div>This mail is send by workflow automatily, please don't reply it. </Div>",
                                           SPContext.Current.Web.CurrentUser.Name,
                                           "" + item["ChangeDescription"],
                                          item["ApproveComments"]);
              try
              {
                  if (string.IsNullOrWhiteSpace(Helper.EditorUsersMail))
                  {
                      this.ErrorMessageLiteral.Visible = true;
                      this.ErrorMessageLiteral.InnerHtml = "Approve successed，but can't find any editor's email aderss，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
                  }
                  else if (!string.IsNullOrWhiteSpace(mailBody))
                  {
                      bool result = Helper.SendMail(Helper.EditorUsersMail, Helper.ApproveUsersEmail, SPContext.Current.Web.CurrentUser.Name + " approved the request", mailBody);

                      if (!result)
                      {
                          this.ErrorMessageLiteral.Visible = true;
                          this.ErrorMessageLiteral.InnerHtml = "Approve successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
                      }
                  }
              }
              catch (Exception ex)
              {
                  this.ErrorMessageLiteral.Visible = true;
                  this.ErrorMessageLiteral.InnerHtml = "Approve successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
              }

              this.Page_Load(null, null);
        }

        protected void RejectButton_Click(object sender, EventArgs e)
        {
            SiteDataOperator.CancelAll();
            string recordId = Request.QueryString["recordId"];
            SPList approveRecords = SPContext.Current.Web.Lists["ApproveRecords"];
            SPListItem item = approveRecords.GetItemById(int.Parse(recordId));
            item["Status"] = ApproveStatus.Rejected;
            item["ApproveDate"] = DateTime.Now;
            item["ApproveComments"] = this.ApproveCommentsTextarea.InnerText;
            item["ApprovedBy"] = new SPFieldUserValue(SPContext.Current.Web, SPContext.Current.Web.CurrentUser.ID, SPContext.Current.Web.CurrentUser.Name);
            item.Update();
            // Send mail

              string  mailBody = string.Format(@"<Div>Dear editors:</Div>
                                                  <Div>{0} have rejected the request:</Div>
                                                  <Div>Change descriptin is:</Div>
                                                  <Div>{1}</Div>
                                                  <Div>Rejected comment is: {2}</Div><br/><br/> 
                                                  <Div>This mail is send by workflow automatily, please don't reply it. </Div>",
                                            SPContext.Current.Web.CurrentUser.Name,
                                            "" + item["ChangeDescription"],
                                           item["ApproveComments"]);
              try
              {
                  if (string.IsNullOrWhiteSpace(Helper.EditorUsersMail))
                  {
                      this.ErrorMessageLiteral.Visible = true;
                      this.ErrorMessageLiteral.InnerHtml = "Rejected successed，but can't find any editor's email aderss，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
                  }
                  else if (!string.IsNullOrWhiteSpace(mailBody))
                  {
                      bool result = Helper.SendMail(Helper.EditorUsersMail, Helper.ApproveUsersEmail, SPContext.Current.Web.CurrentUser.Name + " rejected the request", mailBody);

                      if (!result)
                      {
                          this.ErrorMessageLiteral.Visible = true;
                          this.ErrorMessageLiteral.InnerHtml = "Rejected successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
                      }
                  }
              }
              catch (Exception ex)
              {
                  this.ErrorMessageLiteral.Visible = true;
                  this.ErrorMessageLiteral.InnerHtml = "Approve successed， but notification email failed to send out may be caused by SharePoint Outgoing mail configration issue，please manual send the follow mail to " + Helper.EditorUsers + ":<br>" + mailBody;
              }


            this.Page_Load(null, null);
        }
    }
}
